import React, { useEffect, useState } from "react";
import "./Admin.css";
import {
  message, Spin, Empty,
  Table, Button, Space,
  Drawer, Form, Input,
} from 'antd';
import { 
  giveRequest,
  getadmininfo,
  deleteadmin,
  register,
} from "../../../lib/apiconfig";

const { Column } = Table;

/**
 * @description 管理员信息管理组件
 */
const Admin = () => {
  const [data, setData] = useState(undefined);
  const [drawer, setDrawer] = useState(false);
  const [freshAction, setFreshAction] = useState(false);
  const [newAccount, setNewAccount] = useState({ account: "", password: "" });


  useEffect(() => {
    giveRequest(getadmininfo(0,1000), "GET", null, res => {
      const status = res.status;
      if ( status === "fail" ) {
        message.error("获取数据失败");
        setData(null);
      } else {
        res.data.forEach(item => {
          item["key"] = item.id;
        });
        setData(res.data);
      }
    });
  }, [freshAction]);

  // 删除管理员账户
  const deleteAdminAccount = record => {
    giveRequest(
      deleteadmin, 
      "POST", 
      {
        status: "deleteadmin",
        data: record,
      },
      res => {
        const status = res.status;
        if ( status === "success" ) {
          message.success("删除成功");
          setFreshAction(!freshAction);
        } else {
          message.error("删除失败!");
        }
      }
    );
  };

  // 创建管理员账户
  const newAdminAccount = () => {
    if ( newAccount && newAccount.account && newAccount.password ) {
      giveRequest(
        register,
        "POST",
        {
          status: "register",
          data: newAccount,
        },
        res => {
          const status = res.status;
          if ( status === "fail" ) {
            message.error("创建用户失败!");
          } else if ( status === "warning" ) {
            message.warn("该用户已存在!");
          } else {
            message.success("创建用户成功");
            setNewAccount({ account: "", password: "" });
            setDrawer(false);
            setFreshAction(!freshAction);
          }
        }
      );
    } else {
      message.warn("账户和密码不能为空!");
    }
  }

  return (
    <div className="Admin-page">
    { function() {
      if ( data === undefined )
        return (
          <div className="Admin-loading flex-column-center-center">
            <Spin size="large" />
          </div>
        );
      else if ( data === null ) 
        return (
          <div className="Admin-failed flex-column-center-center">
            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
          </div>
        );
      else
        return (
          <div className="Admin-content flex-column-center-center">
            <Table dataSource={data} className="Admin-table" pagination={{ pageSize: 9, style: { marginRight: "30px" } }}>
              <Column title="管理员ID" dataIndex="id" key="id" />
              <Column title="管理员账号" dataIndex="account" key="account" />
              <Column
                title="操作"
                key="action"
                render={record => (
                  <Space size="middle">
                    <Button 
                      type="link"
                      style={{ padding: 0 }}
                      onClick={() => deleteAdminAccount(record)}
                    >
                      删除账户
                    </Button>
                  </Space>
                )}
              />
            </Table>
            <div className="Admin-new-account flex-row-start-center">
              <Button 
                type="primary" 
                size="large" 
                style={{ width: 150 }}
                onClick = {() => setDrawer(true)}
              >
                创建新账户
              </Button>
            </div>
            <Drawer
              title="创建管理员账户"
              width={360}
              onClose={() => setDrawer(false)}
              visible={drawer}
              footer={
                <div style={{ textAlign: 'right' }}>
                  <Button 
                    style={{ marginRight: 16, width: 80 }}
                    onClick={() => setDrawer(false)}
                  >
                    取消
                  </Button>
                  <Button 
                    type="primary"
                    style={{ width: 80 }}
                    onClick={newAdminAccount}
                  >
                    提交
                  </Button>
                </div>
              }
            >
              <Form 
                layout="vertical" 
                hideRequiredMark
                onValuesChange={data => {
                  const new_account = JSON.parse(JSON.stringify(newAccount));
                  Object.keys(data).forEach(item => {
                    new_account[item] = data[item];
                  });
                  setNewAccount(new_account);
                }}
              >
                <Form.Item label="账号" name="account" rules={[{ required: true, message: "账号不能为空!" }]}>
                  <Input placeholder="请输入账号~" />
                </Form.Item>
                <Form.Item label="密码" name="password" rules={[{ required: true, message: "密码不能为空!" }]}>
                  <Input placeholder="请输入密码~" />
                </Form.Item>  
              </Form>
            </Drawer>
          </div>
        );
    } ()}
    </div>
  );
};

export default Admin;